function [ output_args ] = imsync( imfn,dbg )
%IMSYNC Summary of this function goes here
%  Detailed explanation goes here

if nargin < 2
    dbg=1;
end

im=imloadtogrey(imfn,dbg);

imh = size(im,1);
imw = size(im,2);
vh = zeros(imh, 1);
vv = zeros(1, imw);

ntry=2;
dhlow=1;
dhhigh=imh;
dvlow=1;
dvhigh=imw;
w=8;
for itry=1 : ntry
	for i = 1 : imh
        vh(i)=linevar(im(i,dvlow:dvhigh));
	end
	for j = 1 : imw
        vv(j)=linevar(im(dhlow:dhhigh,j));
	end
	
	dh = ditch(vh,32);
	dv = ditch(vv,32);
    
    seqh=pulseq(dh);
    seqv=pulseq(dv);
    
    [phl, phr, phb, prdh] = periodian(seqh);
    ph = [phl,phb,phr];
    if length(ph)==0
        %% maybe unused
        kThr12=0.05;
        [phl, phr, phb, prdh] = periodian(seqh, kThr12);
        ph = [phl,phb,phr];
    end

    [pvl, pvr, pvb, prdv] = periodian(seqv);
    pv = [pvl,pvb,pvr];
    if length(pv)==0
        %% maybe unused
        kThr12=0.05;
        [pvl, pvr, pvb, prdv] = periodian(seqv,kThr12);
        pv = [pvl,pvb,pvr]
    end
    
    dhlow = max(1, ph(1)-w);
    dhhigh= min(imh, ph(end)+w);
    dvlow = max(1, pv(1)-w);
    dvhigh= min(imw, pv(end)+w);
    
    %% update dh,dv
    dh = dh*0;
    dv = dv*0;
    dh(ph)=1; dv(pv)=1;
    
    if dbg
        %figure; mesh(vh*vv); view(2);
        h=figure; set(h,'Name',sprintf('Try %d',itry));
        h=subplot(2,2,4); plot(vh, [1:length(vh)]); axis([min(vh),max(vh),1,imh]); set(h,'YDir','reverse'); 
        subplot(2,2,1); plot(vv); axis([1,imw,min(vv),max(vv)]);
        subplot(2,2,3); image_grey(im);
        for i = 1 : length(dh)
            if dh(i) == 1
                line([1,imw],[i,i]);
            end
        end
        for j = 1 : length(dv)
            if dv(j) == 1
                line([j,j],[1,imh]);
            end
        end
        
        %figure; stem(dh);
        %figure; stem(dv);
	end 
end




%[beginh,endh,nh] = sync(dh)
%[beginv,endv,nv] = sync(dv)


